import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/route.dart';
import 'package:projectfluttershengyihuatong/service/jsontool.dart';
import 'package:projectfluttershengyihuatong/service/request_manager.dart';
import 'package:projectfluttershengyihuatong/tab4/news_top_model.dart';
import 'package:projectfluttershengyihuatong/tool/extension_int.dart';
import 'package:projectfluttershengyihuatong/tool/public_color.dart';
import 'package:projectfluttershengyihuatong/tool/tool.dart';

import '../service/loginService/logginservice.dart';
class NewsPage extends StatefulWidget {
  const NewsPage({super.key});

  @override
  State<NewsPage> createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {

  @override
  void initState() {
    // TODO: implement initState
    RequestManager.getInstance().dio.get("/api/news/getNewsCateory").then((value){
      final model = BaseModel<List<String>>.fromJson(value.data);
      _streamController.add(model.data ?? []);

    }).onError((error, stackTrace){

    });
    
    super.initState();
  }
  late StreamController<List<String>> _streamController = StreamController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(44),
        child: AppBar(
          backgroundColor: primaryColor,
          title: const Text("资讯", style: TextStyle(color: Colors.white),),
        ),
      ),
      body: StreamBuilder(
        stream: _streamController.stream,
        builder: (context, snapshot){

          if (snapshot.hasData) {
            final dataArr = snapshot.data ?? [];
            final tabs = dataArr.map((e){
              final tab = Tab(text: e);
              return tab;
            }).toList();
            final tabPage = dataArr.map((e){
              return NewTabViewPage(title: e);
            }).toList();
            return DefaultTabController(
              length: dataArr.length,
              child: Container(
                color: colorf9,
                child: Column(
                  children: [
                    Container(
                      color: Colors.white,
                      child: TabBar(
                        tabs: tabs,
                        isScrollable: true,
                        tabAlignment: TabAlignment.start,
                        indicatorColor: primaryColor,
                        labelColor: primaryColor,
                        labelStyle: const TextStyle(fontSize: 16),
                        unselectedLabelColor: color33,
                        unselectedLabelStyle: const TextStyle(fontSize: 14),
                      ),
                    ),
                    Expanded(child: TabBarView(children: tabPage))
                  ],
                ),
              ),
            );
          }

          return GestureDetector(
            onTap: (){

            },
            child: Container(
              color: Colors.red,
              child: const Center(
                child: Text("没有数据"),
              ),
            ),
          );



        },

      ),
    );
  }
}


enum LoadMoreStatus {more, loading, noMore,error}
class NewTabViewPage extends StatefulWidget {
  const NewTabViewPage({super.key, required this.title});
  final String title;

  @override
  State<NewTabViewPage> createState() => _NewTabViewPageState();
}

class _NewTabViewPageState extends State<NewTabViewPage> {
  @override
  void initState() {
    // TODO: implement initState
    request();


    _scrollController.addListener(() {
      if (_scrollController.position.extentAfter == 0) {
        //   滚动到底部加载更多数据

        loadMore();
      }
    });


    super.initState();
  }
  List<NewsBottomModel> dataArr = [];
  LoadMoreStatus _loadMoreStatus = LoadMoreStatus.loading;

  request() {
    RequestManager.getInstance().dio.get("/api/news/newsList",queryParameters: {"category_name": widget.title, "limit": 10, "page": page}).then((value){
      final model = BaseModel<PageEntity<NewsBottomModel>>.fromJson(value.data);
      if (page == 1) {
        dataArr = model.data?.list ?? [];
      }else {
        dataArr += model.data?.list ?? [];
      }
      final total = model.data?.total ?? 0;
      dataArr = model.data?.list ?? [];
      if (total > dataArr.length) {
        _loadMoreStatus = LoadMoreStatus.more;
      }else if (total == dataArr.length) {
        _loadMoreStatus = LoadMoreStatus.noMore;
      }
      setState(() {

      });

    }).onError((error, stackTrace){

    });

  }
  Future<void> refresh() async {
    page = 1;
    _loadMoreStatus = LoadMoreStatus.loading;
    final response = await RequestManager.getInstance()
        .dio
        .get("/api/news/newsList", queryParameters: {
      "category_name": widget.title,
      "limit": 10,
      "page": page
    });
    final model = BaseModel<PageEntity<NewsBottomModel>>.fromJson(response.data);
    final total = model.data?.total ?? 0;
    dataArr = model.data?.list ?? [];
    if (total > dataArr.length) {
      _loadMoreStatus = LoadMoreStatus.more;
    }else if (total == dataArr.length) {
      _loadMoreStatus = LoadMoreStatus.noMore;
    }

    return Future<void>.value();


  }
  loadMore() {
    if (_loadMoreStatus == LoadMoreStatus.noMore) {
      return;
    }


    if (_loadMoreStatus == LoadMoreStatus.loading) {
      return;
    }

    page++;
    request();
  }
  int page = 1;
  ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    String tips = "";
    if (_loadMoreStatus == LoadMoreStatus.noMore) {
      tips = "没有更多数据";
    }
    if (_loadMoreStatus == LoadMoreStatus.loading) {
      tips = "正在加载中";
    }
    if (_loadMoreStatus == LoadMoreStatus.more) {
      tips = "下拉加载更多数据";
    }
    return Padding(
      padding: const EdgeInsets.fromLTRB(9, 10, 9, 9),
      child: RefreshIndicator(

        onRefresh: refresh,
        child: CustomScrollView(
          slivers: [
            SliverPadding(
              padding: const EdgeInsets.all(10),
              sliver: SliverList.separated(
                  itemBuilder: (context, index) {
                    final model = dataArr[index];
                    return NewsBottomListCell(model: model);

                  },
                  separatorBuilder: (context, index) {
                    return Divider(color: colorf9, height: 1, thickness: 1,);

                  }, itemCount: dataArr.length),
            ),
          //   填充剩余空间
            SliverFillRemaining(
              hasScrollBody: false,
              fillOverscroll: false,
              child: Container(),
            ),
            SliverToBoxAdapter(
              child: Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.only(bottom: 10),
                height: 40,
                child: Text(tips),
              ),

            ),
          ],
        ),
      ),
    );
  }
}

class NewsBottomListCell extends StatelessWidget {
  const NewsBottomListCell({
    super.key,
    required this.model,
  });

  final NewsBottomModel model;

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(6),
      child: GestureDetector(
        onTap: (){
          debugPrint(model.skipUrl);
          Get.toNamed(RouteNames.WEBPAGE, arguments: {"url": model.skipUrl,"title": model.title});
        },
        child: Container(
          height: 116.adapt(),
          color: Colors.white,
          child: Row(
            children: [
              Expanded(
                child: Container(
                  padding: const EdgeInsets.fromLTRB(15, 10, 10, 5),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                        Container(
                          height: 80,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                model.title,
                                style: TextStyle(
                                    color: color33,
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold),
                                maxLines: 1,
                                overflow: TextOverflow.clip,
                              ),
                              const SizedBox(height: 5,),
                              Text(
                                model.description,
                                style: TextStyle(
                                    color: color66,
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                          ),
                        ),

                        Container(
                          height: 20,
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(assetImage("icon-timer"),width: 14.adapt(),height: 14.adapt(),fit: BoxFit.fill,),
                              const SizedBox(width: 5,),
                              Text(model.publish, style: TextStyle(color: color99, fontSize: 12),)
                            ],
                          ),
                        )

                      ],
                  ),
                ),
              ),
                Image.network(
                  model.cover,
                  fit: BoxFit.fill,
                  width: 117 / 86 * 87.adapt(),
                  height: 87.adapt(),
                ),
              const SizedBox(width: 5,)
              ],
          ),
        ),
      ),
    );
  }
}

